package cn.juforg.gobang;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import cn.juforg.gobang.Constants.GESTUREMODE;
import cn.juforg.gobang.interfaces.ChessBoardDao;
import cn.juforg.gobang.interfaces.ChessBoardImpl;
import cn.juforg.gobang.listener.ChessboardGestureListener;
import cn.juforg.gobang.player.BaseAI;
import cn.juforg.gobang.player.BasePlayer;
import cn.juforg.gobang.player.HumanPlayer;
/**
 * 1. 优化 保存好所有的棋子对象，不需要每次新建
 * 2. 优化 生成棋子的方法
 * 
 * 
 * 
 * 
 * 
 * 
 * @author Juforg
 * 棋盘类
 */
public class ChessBoard extends View implements ChessBoardDao{

	
	//游戏状态常量
	public static final int READY = 1;				//等待开始
	public static final int RUNNING = 2;				//正在游戏中
	public static final int PLAYER_ONE_LOST = 3;		//玩家一输了
	public static final int PLAYER_TWO_LOST = 4;		//玩家二输了
	public static final boolean PLAYER1FLAG = true;
	public static final boolean PLAYER2FLAG = false;
	
	public static final int BLACK = 1;
	public static final int NEW_BLACK = 3;			//黑色棋子
	public static final int WHITE = 0;					
	public static final int NEW_WHITE = 2;			//白色棋子
	public static final int EMPTY = 4;				//无子
	
	public static int chessSize = 32;					//棋子大小
	private int oldChessSize = chessSize;
	
	private static int currentStatus = READY;			//当前状态（默认为等待开始）

	public static int maxX;							//屏幕的最大坐标（即右下角点的坐标）从零开始
	public static int maxY;
	private int oldMaxX ;
	private int oldMaxY ;
	
	public static int screen_width;					//屏幕大小
	public static int screen_height;
	
	public static int xLeftOffset;							//第一点偏离左上角从像数，为了棋盘居中(像素偏移）
	public static int yUpOffset;
	public static int xRightOffset;							//第一点偏离左上角从像数，为了棋盘居中(像素偏移）
	public static int yDownOffset;
	public static int oldXLeftOffset;						//第一点偏离左上角从像数，为了棋盘居中(像素偏移）
	public static int oldYUpOffset;
	public static int oldXRightOffset;						//第一点偏离左上角从像数，为了棋盘居中(像素偏移）
	public static int oldYDownOffset;
	
	public static int zoomXOffset = 0;					//棋格偏移量
	public static int zoomYOffset = 0;
	public static int oldZoomXOffset = 0;				//棋格偏移量
	public static int oldZoomYOffset = 0;
	
	public static Chess zoomChess ;						//处在缩放中心位置的棋子
	
	private List<Line> lines = new ArrayList<Line>();	//棋盘上所有的线
//	private List<Chess> chesses = new ArrayList<Chess>();//棋盘上所有的棋子
	
	public static int[][] chessArray = new int[Constants.CHESSBAORD_TYPE][Constants.CHESSBAORD_TYPE];//棋盘上所有的点
	
	private BasePlayer player1 = new HumanPlayer(PLAYER1FLAG);	//玩家一(默认为人类玩家）
	private BasePlayer player2 ;						//玩家二
//	private BasePlayer currentTrun = player1;			//当前玩家 默认玩家1先
	private boolean currentPlayer = PLAYER1FLAG;		//true为玩家1 false为玩家2
	
	private Paint paint = new Paint();					//画笔对象
	
	private Bitmap[] chessColorArray = new Bitmap[4];		//不同颜色的Bigmap数组
	
	private GESTUREMODE gestureMode = GESTUREMODE.NONE; 
	private Chess actionDownChess ,actionUpChess;			//触屏时的棋子 ，放开时的棋子
	private float orgDistance, lastDistance;				//两触点距离
	private Activity aty;
	public static RefreshHandler computerRun;
	private int delayMillis = 400 ;
	public static Long startTime;
	private GestureDetector myGestureDetector;
	
	
	Resources r = this.getContext().getResources();
	
	public ChessBoard(Context context, AttributeSet attrs) {
		super(context, attrs);
		setFocusable(true);
		this.fillChessArrays(chessColorArray, BLACK, r.getDrawable(R.drawable.black_chess), chessSize);
		this.fillChessArrays(chessColorArray, NEW_BLACK, r.getDrawable(R.drawable.new_black_chess), chessSize);
		this.fillChessArrays(chessColorArray, WHITE, r.getDrawable(R.drawable.white_chess), chessSize);
		this.fillChessArrays(chessColorArray, NEW_WHITE, r.getDrawable(R.drawable.new_white_chess), chessSize);
		computerRun =  new RefreshHandler();
		
		//设置画线时用的颜色
        paint.setColor(Color.LTGRAY);
        
        //设置手势相关
        myGestureDetector = new GestureDetector(context, new ChessboardGestureListener(this));
        //setLongClickable(true);
        myGestureDetector.setIsLongpressEnabled(true);
	}
	
	int zoomPointLeft,zoomPointRight,zoomPointUp,zoomPointDown;
	
	private void getZoomPointRound(int w, int h){
		zoomPointLeft = (int)FloatMath.floor((ZoomPoint.getInstance().getX()-xLeftOffset)/chessSize);		//缩放点左边容纳棋子个数
		zoomPointRight = (int)FloatMath.floor((w-ZoomPoint.getInstance().getX()-xRightOffset)/chessSize);
		zoomPointUp = (int)FloatMath.floor((ZoomPoint.getInstance().getY()-yUpOffset)/chessSize);
		zoomPointDown = (int)FloatMath.floor((h-ZoomPoint.getInstance().getY()-yDownOffset)/chessSize);
		zoomPointLeft = zoomPointLeft>(zoomChess.getX()+1)? (zoomChess.getX()+1):zoomPointLeft;
		zoomPointRight = zoomPointRight>(Constants.CHESSBAORD_TYPE-zoomChess.getX()-1)? (Constants.CHESSBAORD_TYPE-zoomChess.getX()-1):zoomPointRight;
		zoomPointUp = zoomPointUp>(zoomChess.getY()+1)? (zoomChess.getY()+1):zoomPointUp;
		zoomPointDown = zoomPointDown>(Constants.CHESSBAORD_TYPE-zoomChess.getY()-1)? (Constants.CHESSBAORD_TYPE-zoomChess.getY()-1):zoomPointDown;
		
	}
	
	/**
	 * 初始化棋盘的一些参数，包括棋盘最大坐标，偏移量，和产生棋盘线
	 * @param w
	 * @param h
	 */
	private void initChessBoardParam(int w, int h){
		//maxX = (int) Math.floor(w / chessSize);
		//maxY = (int) Math.floor(h / chessSize);
//		int zoomPointLeft = (int)FloatMath.floor(ZoomPoint.getInstance().getX()/chessSize);		//缩放点左边容纳棋子个数
//		int zoomPointRight = (int)FloatMath.floor((w-ZoomPoint.getInstance().getX())/chessSize);
//		int zoomPointUp = (int)FloatMath.floor(ZoomPoint.getInstance().getY()/chessSize);
//		int zoomPointDown = (int)FloatMath.floor((h-ZoomPoint.getInstance().getY())/chessSize);
//		zoomPointLeft = zoomPointLeft>(zoomChess.getX()+1)? (zoomChess.getX()+1):zoomPointLeft;
//		zoomPointRight = zoomPointRight>(Constants.CHESSBAORD_TYPE-zoomChess.getX()-1)? (Constants.CHESSBAORD_TYPE-zoomChess.getX()-1):zoomPointRight;
//		zoomPointUp = zoomPointUp>(zoomChess.getY()+1)? (zoomChess.getY()+1):zoomPointUp;
//		zoomPointDown = zoomPointDown>(Constants.CHESSBAORD_TYPE-zoomChess.getY()-1)? (Constants.CHESSBAORD_TYPE-zoomChess.getY()-1):zoomPointDown;
			
		xLeftOffset = (int) (ZoomPoint.getInstance().getX()-chessSize * zoomPointLeft);
		xRightOffset = (int) (w-ZoomPoint.getInstance().getX()-chessSize * zoomPointRight);
		yUpOffset = (int) (ZoomPoint.getInstance().getY()-chessSize * zoomPointUp);
		yDownOffset = (int) (h-ZoomPoint.getInstance().getY()-chessSize * zoomPointDown);
		
		getZoomPointRound(w, h);
		maxX = zoomPointLeft + zoomPointRight>0?zoomPointLeft + zoomPointRight:0;//个数转换为数组下标 -1
		maxY = zoomPointUp + zoomPointDown>0?zoomPointUp + zoomPointDown:0;
		
		//以下可能无用
		if (maxX > Constants.CHESSBAORD_TYPE) {
			maxX = Constants.CHESSBAORD_TYPE-1;
			maxY = Constants.CHESSBAORD_TYPE-1;
		}else if (maxX < 5) {
			maxX = 5;
			chessSize = oldChessSize;
			maxY = (int) Math.floor(h / chessSize);
		}
		if (maxY > Constants.CHESSBAORD_TYPE) {
			maxY = Constants.CHESSBAORD_TYPE-1;
		}
		
//		//设置X、Y座标微调值，目的整个框居中
//		xOffset = ((w - (chessSize * maxX)) / 2);
//		yOffset = ((h - (chessSize * maxY)) / 2);
		if (maxX != Constants.CHESSBAORD_TYPE-1) {
			zoomXOffset = zoomChess.getX()- zoomPointLeft+1;
			if (maxY<Constants.CHESSBAORD_TYPE-1) {
				zoomYOffset = zoomChess.getY()- zoomPointUp+1;
			}
		}
		
	     //创建棋盘上的线条
	     this.createLines();
	     
	     this.recordInfo();
	}
	
	private void recordInfo(){
		//记录信息
		oldMaxX = maxX;
		oldMaxY = maxY;
		oldXLeftOffset = xLeftOffset;
		oldXRightOffset = xRightOffset;
		oldYUpOffset = yUpOffset;
		oldYDownOffset = yDownOffset;
		oldZoomXOffset = zoomXOffset;
		oldZoomYOffset = zoomYOffset;
	}
	
	/*
	 * 初始横线和竖线的数目
	 * @see android.view.View#onSizeChanged(int, int, int, int)
	 */
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		Constants.TITLE_STATUS_OFFSET = Constants.WINDOW_HEIGHT - h;
		chessSize = (int) Math.floor(w / Constants.CHESSBAORD_TYPE);
		maxX = maxY =Constants.CHESSBAORD_TYPE;
		BaseAI.CalculateRange.xstart = Constants.CHESSBAORD_TYPE-1;
		BaseAI.CalculateRange.ystart = Constants.CHESSBAORD_TYPE-1;
		
       /* BaseAI.CalculateRange.xstart = maxX-1;
        BaseAI.CalculateRange.ystart = maxY-1;
		//设置X、Y座标微调值，目的整个框居中
		 xOffset = ((w - (chessSize * maxX)) / 2);
	     yOffset = ((h - (chessSize * maxY)) / 2);
	   //创建棋盘上的线条
	     this.createLines();*/
		screen_width = w;
		screen_height = h;
		Log.i("view height",screen_height+"");
		Log.i("view width",screen_width+"");
	   //初始化棋盘上所有空白点
	     chessArray = new int[Constants.CHESSBAORD_TYPE][Constants.CHESSBAORD_TYPE];
	     ZoomPoint.getInstance().set(w / 2, screen_height / 2);
	     zoomChess = new Chess(Constants.MID_POINT-1, Constants.MID_POINT-1);
	     zoomPointLeft = zoomPointRight = zoomPointUp = zoomPointDown = Constants.MID_POINT - 1 ;
	     initChessBoardParam(screen_width, screen_height);
	     BaseAI.weights = new int[Constants.CHESSBAORD_TYPE][Constants.CHESSBAORD_TYPE];
	     BaseAI.weights[0][0]=-1;
	     for (int i = 0; i < Constants.CHESSBAORD_TYPE; i++) {
			for (int j = 0; j < Constants.CHESSBAORD_TYPE; j++) {
				//Log.d("clean chessboard", "i:"+i+",j:"+j);
				chessArray[i][j] = EMPTY;
			}
		}
	}
	private void logXY(){
		Log.d("log invoke", "xLeftOffset="+xLeftOffset+", xRightOffset="+xRightOffset+", yUpOffset="+yUpOffset+", yDownOffset="+yDownOffset);
		
	}
	//计算棋盘上所有的线
    private void createLines(){
    	lines.clear();
    	logXY();
    	for (int i = 1; i <= maxX; i++) {//竖线
    		lines.add(new Line(xLeftOffset+i*chessSize-chessSize/2, yUpOffset, xLeftOffset+i*chessSize-chessSize/2, yUpOffset+maxY*chessSize));
		}
    	for (int i = 1; i <= maxY; i++) {//横线
    		lines.add(new Line(xLeftOffset, yUpOffset+i*chessSize-chessSize/2, xLeftOffset+maxX*chessSize, yUpOffset+i*chessSize-chessSize/2));
		}
    }

	
	//处理触摸事件
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		//还没有开局，或者是按下事件，不处理，只处理开局后的触摸弹起事件
		if(!this.isRunning(currentStatus) ){
			Log.i("motion", "event.getAction()="+event.getAction());
			System.out.println("还没开局！");
			return true;
		}
		/** 处理单点、多点触摸 **/
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			gestureMode = GESTUREMODE.NONE;
			actionDownChess = this.generateChess(event.getX(), event.getY());
			Log.d("actionDownChess", actionDownChess.toString());
			ZoomPoint.getInstance().set(event.getX(), event.getY());
			zoomChess = ChessBoardImpl.generateChess(event.getX(), event.getY());
			break;
		case MotionEvent.ACTION_UP:
			if(gestureMode == GESTUREMODE.NONE){
				actionUpChess = this.generateChess(event.getX(), event.getY());
				Log.d("actionUpChess", actionUpChess.toString());
				if (!actionUpChess.equals(actionDownChess)) {
					Log.d("action up", "不是同一点");
					break;
				}
				//是否轮到我下
				if(this.isMyTurn(player1, currentPlayer) && isTouchUseable(event)){
					this.playerRun(player1, event);
					this.refressCanvas();
					if (BaseAI.class.isAssignableFrom(player2.getClass()) && this.isMyTurn(player2, currentPlayer) && PLAYER_TWO_LOST != ChessBoard.currentStatus) {
						computerRun.computerRunAfter();
					}
					//return false;
				}else if (this.isMyTurn(player2, currentPlayer) && !BaseAI.class.isAssignableFrom(player2.getClass())) {
					this.playerRun(player2, event);
					//return false;
				}
			}
			gestureMode = GESTUREMODE.NONE;
			Log.d("gesture ", "NONE");
			break;
		// 多点触摸
		case MotionEvent.ACTION_POINTER_DOWN:
			Log.d("gesture ", "ZOOM");
			gestureMode = GESTUREMODE.ZOOM;
			ChessBoardImpl.generateMidPoint(event);
			orgDistance = ChessBoardImpl.getTwoPointDistance(event);
			break;
		case MotionEvent.ACTION_POINTER_UP:
			gestureMode = GESTUREMODE.DRAG;
			Log.d("gesture ", "DRAG");
			ZoomPoint.getInstance().set(event.getX(), event.getY());
			break;
		case MotionEvent.ACTION_MOVE:
			if (gestureMode == GESTUREMODE.ZOOM) {
				lastDistance = ChessBoardImpl.getTwoPointDistance(event);
				if ( Math.abs(orgDistance-lastDistance) >5f) {
					float zoomRatio = lastDistance / orgDistance;
					zoomChessBoard(zoomRatio);
					Log.d("zoomRatio", "zoomRatio:"+zoomRatio);
					orgDistance = lastDistance;
				}
			}else {
				gestureMode = GESTUREMODE.DRAG;
				dragChessBoard(event);
				Log.d("gesture ", "drag-1");
			}
			break;
		default:
			break;
		}
		return true;
	}
	
	private boolean isTouchUseable(MotionEvent event){
		if (event.getX()<xLeftOffset || event.getY() <yUpOffset || event.getX()>xLeftOffset+Constants.CHESSBAORD_TYPE*chessSize || event.getY()>yUpOffset+Constants.CHESSBAORD_TYPE*chessSize) {
			return false;
		}
		return true;
	}

   
	public class RefreshHandler extends Handler {
		//这个方法主要在指定的时刻发一个消息
        public void computerRunAfter() {
        	this.removeMessages(0);
        	startTime = System.currentTimeMillis();
			Log.i("handler", "thread name:"+Thread.currentThread().getName()+"| thread id:"+Thread.currentThread().getId());
        	//电脑走一步棋子
			player2.run();
        }
        
        //收到消息
        @Override
        public void handleMessage(Message msg) {
        	playerRun(player2, new Chess(BaseAI.bestPoint.getX(), BaseAI.bestPoint.getY()));
        	long tmp =System.currentTimeMillis()-startTime;
        	if (tmp<delayMillis) {
				try {
					Thread.sleep(delayMillis-tmp);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
    		//刷新一下
        	refressCanvas();
        }
    };
    
    @Override
    protected void onDraw(Canvas canvas) {
    	this.drawChssboardLines(lines, canvas, paint);
    	this.drawChess(canvas, chessArray, chessColorArray,paint);
    }
    
	public static int getMaxX() {
		return maxX;
	}

	public static int getMaxY() {
		return maxY;
	}

	public static int getChessSize() {
		return chessSize;
	}
	
	public static int getCurrentStatus() {
		return currentStatus;
	}

	public static void setCurrentStatus(int currentStatus) {
		ChessBoard.currentStatus = currentStatus;
	}


	public boolean getCurrentPlayer() {
		return currentPlayer;
	}

	public void setCurrentPlayer(boolean currentPlayer) {
		this.currentPlayer = currentPlayer;
	}
	public void setChessArray(int[][] chessArray) {
		ChessBoard.chessArray = chessArray;
	}

	public void setPlayer2(BasePlayer player2) {
		this.player2 = player2;
	}

	public Activity getAty() {
		return aty;
	}

	public void setAty(Activity aty) {
		this.aty = aty;
	}

	
	@Override
	public void setStatus(int newStatus) {
		ChessBoard.setCurrentStatus(newStatus);
    	if(newStatus==ChessBoard.PLAYER_TWO_LOST){
			//提示玩家2输了
			newStatus = ChessBoard.READY;
		}else if(newStatus==ChessBoard.RUNNING){
		}else if(newStatus==ChessBoard.READY){
		}else if(newStatus==ChessBoard.PLAYER_ONE_LOST){
			//提示玩家1输了
			ChessBoard.setCurrentStatus(ChessBoard.READY);
		}		
	}

	@Override
	public boolean isMyTurn(BasePlayer player, boolean currentPlayer) {
		if(player!=null){
			return player.getMyFlag()==currentPlayer;
		}
		return false;
	}
	
	@Override
	public void drawChssboardLines(List<Line> lines ,Canvas canvas, Paint paint) {
    	for (Line line : lines) {
    		canvas.drawLine(line.getXstart(), line.getYstart(), line.getXstop(), line.getYstop(), paint);
    		//Log.d("draw line", line.toString());
		}
	}

	@Override
	public void drawChess(Canvas canvas, int[][] chessArray,
			Bitmap[] chessColorArray, Paint paint) {
			for (int i = 0; i < ChessBoard.maxX; i++) {
				for (int j = 0; j < ChessBoard.maxY; j++) {
					//Log.d("draw chess", "x:"+(i+zoomXOffset)+",y:"+(j+zoomYOffset)+",j:"+j+",ChessBoard.maxY:"+ChessBoard.maxY);
					//Log.d("draw chessArray", "chessArray[i][j]："+chessArray[i][j]);
					//Log.d("draw chessArray", "chessArray[i+zoomXOffset][j+zoomYOffset]："+chessArray[i+zoomXOffset][j+zoomYOffset]);
					if(chessArray[i+zoomXOffset][j+zoomYOffset]!= EMPTY){
//						int a = chessArray[i][j]-48;
						canvas.drawBitmap(chessColorArray[chessArray[i+zoomXOffset][j+zoomYOffset]],i*ChessBoard.chessSize
							+ChessBoard.xLeftOffset,j*ChessBoard.getChessSize()+ChessBoard.yUpOffset,paint);
					
					}
				}
			}
			drawWeight(canvas, chessArray);
	}
	public void drawWeight(Canvas canvas,int[][] chessArray) {
		for (int i = BaseAI.CalculateRange.xstart<zoomXOffset?zoomXOffset+1:BaseAI.CalculateRange.xstart;
		i <= (BaseAI.CalculateRange.xstop<zoomXOffset+maxX?BaseAI.CalculateRange.xstop:zoomYOffset+1+maxX); i++) {
			for (int j = BaseAI.CalculateRange.ystart<zoomYOffset?zoomYOffset+1:BaseAI.CalculateRange.ystart; 
			j <= (BaseAI.CalculateRange.ystop<zoomYOffset+maxY?BaseAI.CalculateRange.ystop:zoomYOffset+1+maxY); j++) {
//				if(chessArray[i][j]!='4'){
					//Log.d("draw weight", "i:"+i+",j:"+j);
					drawPointWeight(canvas, i, j);
					
//				}
			}
		}
	}
	public void drawPointWeight(Canvas canvas,int i, int j){
	        Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	        numPaint.setTextSize(10);
	        numPaint.setColor(Color.MAGENTA);
	        numPaint.setTextAlign(Align.CENTER);
	        canvas.drawText(""+BaseAI.weights[i][j], (float)(i-zoomXOffset+0.5)*ChessBoard.chessSize+xLeftOffset, (float)(j-zoomYOffset+0.5)*ChessBoard.chessSize+yUpOffset, numPaint);
//	        BaseAI.weights[i][j]= 0;
	}
	@Override
	public void restart() {
		int[][] c = new int[ChessBoard.getMaxX()][ChessBoard.getMaxY()];
	     for (int i = 0; i < ChessBoard.getMaxX(); i++) {
				for (int j = 0; j < ChessBoard.getMaxY(); j++) {
					c[i][j] = EMPTY;
				}
			}
		this.setChessArray(c);
		player1.setPreviousChess(null);
		player2.setPreviousChess(null);
		BaseAI.CalculateRange.xstart = Constants.CHESSBAORD_TYPE;
		BaseAI.CalculateRange.xstop = 0;
        BaseAI.CalculateRange.ystart = Constants.CHESSBAORD_TYPE;
        BaseAI.CalculateRange.ystop = 0;
		this.setPlayerRun(PLAYER1FLAG);
		this.refressCanvas();
	}

	@Override
	public boolean isRunning(int currentStatus) {
		if(currentStatus == ChessBoard.RUNNING){
			return true;
		}
		return false;
		
	}

	@Override
	public synchronized void playerRun(BasePlayer player, Chess chess) {
			Log.i("old_currentPlayer", this.getCurrentPlayer()?"player1":"player2");
			if(null!=chess && this.setChess(chess, player)){
			this.setCurrentPlayer(!this.getCurrentPlayer());
			if(player.hasWin(chess, player.getMyFlag(), chessArray)){
				this.setStatus(player.getMyFlag()?ChessBoard.PLAYER_TWO_LOST:ChessBoard.PLAYER_ONE_LOST);
				new  AlertDialog.Builder(getAty())
				.setTitle(R.string.game_over)  
				.setMessage(player.getMyFlag()?R.string.player_two_lost:R.string.player_one_lost)  
				.setPositiveButton(R.string.restart ,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								restart();
					        	setStatus(ChessBoard.RUNNING);
								dialog.dismiss();
								}
							}
				        )  
				.setNegativeButton(R.string.return_menu , 
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								getAty().finish();
								dialog.dismiss();
						}
					}
				)
				.show();
			}
			
			generateCalculateRange(chess);//产生计算边界值（提高AI效率）
			Log.i("new_currentPlayer", this.getCurrentPlayer()?"player1":"player2");
			}
			else {
				Log.i("error", "no best point ");
			}
	}

	@Override
	public void playerRun(BasePlayer player, MotionEvent event) {
		Chess chess = this.generateChess(event.getX(), event.getY());
		this.playerRun(player, chess);
	}

	@Override
	public Chess generateChess(Float x, Float y) {
		
		Chess  chess = new Chess(0,0);
		for(int i = 0; i <= ChessBoard.getMaxX();i++){
			if((i*ChessBoard.getChessSize()+ChessBoard.xLeftOffset) <= x 
					&& x<= ((i+1)*ChessBoard.getChessSize()+ChessBoard.xLeftOffset)){
				chess.setX(i);
				break;
			}
		}
		for(int i = 0; i <= ChessBoard.getMaxY();i++){
			if((i*ChessBoard.getChessSize()+ChessBoard.yUpOffset) <= y 
					&& y<= ((i+1)*ChessBoard.getChessSize()+ChessBoard.yUpOffset)){
				chess.setY(i);
				break;
			}
		}
		//Log.d("chessboard", "new chess:"+chess.toString());
		return chess;
	}


	@Override
	public void refressCanvas() {
		this.invalidate();		
	}

	private void refreshChessArrays(){
		this.fillChessArrays(chessColorArray, BLACK, r.getDrawable(R.drawable.black_chess), chessSize);
		this.fillChessArrays(chessColorArray, NEW_BLACK, r.getDrawable(R.drawable.new_black_chess), chessSize);
		this.fillChessArrays(chessColorArray, WHITE, r.getDrawable(R.drawable.white_chess), chessSize);
		this.fillChessArrays(chessColorArray, NEW_WHITE, r.getDrawable(R.drawable.new_white_chess), chessSize);
	}
	
	@Override
	public void fillChessArrays(Bitmap[] chessColorArray, int color,
			Drawable drawable, int chessSize) {
		 Bitmap bitmap = Bitmap.createBitmap(chessSize, chessSize, Bitmap.Config.ARGB_8888);
	        Canvas canvas = new Canvas(bitmap);
	        drawable.setBounds(0, 0, chessSize, chessSize);
	        drawable.draw(canvas);
	        chessColorArray[color] = bitmap;
	}

	@Override
	public void setPlayerRun(BasePlayer player) {
		this.setCurrentPlayer(player.getMyFlag());
	}
	
	@Override
	public void setPlayerRun(boolean playerFlag) {
		this.setCurrentPlayer(playerFlag);
	}

	@Override
	public boolean setChess(Chess chess, BasePlayer player) {
		if (EMPTY == chessArray[chess.getX()][chess.getY()]) {
				if (null != player.getPreviousChess()) {
					chessArray[player.getPreviousChess().getX()][player.getPreviousChess().getY()] = player.getOldChessFlag();
				}
				player.setPreviousChess(chess);//将当前棋存作 前一步棋
				chessArray[chess.getX()][chess.getY()] = player.getNewChessFlag();
			return true;
		}
		return false;
			
	}
	
	
	/**
	 * 拖动棋盘
	 * @param event
	 */
	public void dragChessBoard(MotionEvent event){
		int xDragOffset,yDragOffset; //拖动量 像素
		xDragOffset = (int) (event.getX()-ZoomPoint.getInstance().getX());
		yDragOffset = (int) (event.getY()-ZoomPoint.getInstance().getY());
//		getZoomPointRound(screen_width, screen_height);
		//if (zoomPointLeft*chessSize + xLeftOffset < event.getX() || zoomPointRight * chessSize +xRightOffset <screen_width-event.getX()) {
		if (zoomXOffset == 0) {
			xLeftOffset =  xDragOffset + xLeftOffset > 0 ? xDragOffset + xLeftOffset : 0;
		}
		if (!(zoomXOffset+maxX< Constants.CHESSBAORD_TYPE-1)) {
			xRightOffset = xDragOffset < xRightOffset ? xRightOffset-xDragOffset : 0 ;
		}
		maxX = (screen_width-xLeftOffset-xRightOffset )/chessSize;
		zoomXOffset = zoomXOffset - (int) FloatMath.floor(xDragOffset/chessSize);
			
		if (zoomYOffset == 0) {
			yUpOffset =  yDragOffset + yUpOffset  > 0 ? yDragOffset + yUpOffset : 0;
		}
		if(!(zoomYOffset+maxY< Constants.CHESSBAORD_TYPE-1)) {
			yDownOffset = yDragOffset < yDownOffset ? yDownOffset-yDragOffset : 0 ;
		}
		maxY = (screen_height-yUpOffset-yDownOffset)/chessSize;
		zoomYOffset = zoomYOffset - (int) FloatMath.floor(yDragOffset/chessSize);
			
		if (zoomXOffset<0) {
			zoomXOffset=0;
		}else if (zoomXOffset > Constants.CHESSBAORD_TYPE-1) {
			zoomXOffset = Constants.CHESSBAORD_TYPE-1;
		}
		if( zoomYOffset < 0) {
			zoomYOffset= 0;
		}else if(zoomYOffset > Constants.CHESSBAORD_TYPE-1){
			zoomYOffset = Constants.CHESSBAORD_TYPE-1;
		}
		//maxX = Constants.CHESSBAORD_TYPE - 1 - zoomXOffset;
		//maxY = Constants.CHESSBAORD_TYPE - 1 - zoomYOffset;
		ZoomPoint.getInstance().set(event.getX(), event.getY());
		this.createLines();
		refressCanvas();
	}
	@Override
	public void zoomChessBoard(float zoomRatio) {
		oldChessSize = chessSize;
		chessSize = Math.round(chessSize * zoomRatio);
		Log.d("chessboard", "chessSize:"+chessSize);
		initChessBoardParam(screen_width, screen_height);
		refreshChessArrays();  //重新准备棋子对象
		this.recordInfo();
		refressCanvas();
	}

	public void generateCalculateRange(Chess chess){
		if(chess.getX()-2 <= BaseAI.CalculateRange.xstart){
			if ((chess.getX()-2)>=0) {
				BaseAI.CalculateRange.xstart=chess.getX()-2;
			}else if ((chess.getX()-1)>=0) {
				BaseAI.CalculateRange.xstart=chess.getX()-1;
			} else {
				BaseAI.CalculateRange.xstart=chess.getX();
			}
		}
		if (chess.getX()+2>=BaseAI.CalculateRange.xstop ) {
			if ((chess.getX()+2)<Constants.CHESSBAORD_TYPE) {
				BaseAI.CalculateRange.xstop=chess.getX()+2;
			}else if ((chess.getX()+1)<Constants.CHESSBAORD_TYPE) {
				BaseAI.CalculateRange.xstop=chess.getX()+1;
			} else {
				BaseAI.CalculateRange.xstop=chess.getX();
			}
		}
		if(chess.getY()-2 <= BaseAI.CalculateRange.ystart){
			if ((chess.getY()-2)>=0) {
				BaseAI.CalculateRange.ystart=chess.getY()-2;
			} else if ((chess.getY()-1)>=0) {
				BaseAI.CalculateRange.ystart=chess.getY()-1;
			} else {
				BaseAI.CalculateRange.ystart=chess.getY();
			}
		}
		if (chess.getY()+2 >= BaseAI.CalculateRange.ystop) {
			if ((chess.getY()+2)<Constants.CHESSBAORD_TYPE) {
				BaseAI.CalculateRange.ystop=chess.getY()+2;
			} else if ((chess.getY()+1)<Constants.CHESSBAORD_TYPE) {
				BaseAI.CalculateRange.ystop=chess.getY()+1;
			} else {
				BaseAI.CalculateRange.ystop=chess.getY();
			}
		}
		Log.i("calculateRang", "x:"+BaseAI.CalculateRange.xstart+"-->"+BaseAI.CalculateRange.xstop);
		Log.i("calculateRang", "Y:"+BaseAI.CalculateRange.ystart+"-->"+BaseAI.CalculateRange.ystop);
	}
	
	
}
